using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using Colorprj.Masters ;

using Colorprj.Common;
namespace Colorprj
{
    public partial class frmInvoice : Form
    {

        //BindingSource parentBS = new BindingSource();
        //BindingSource childBS = new BindingSource();
        //BindingSource filteredChildBS = new BindingSource();
        ProductMasterData pmd = new ProductMasterData();
        Invoice.InvoiceManager cm = new Colorprj.Invoice.InvoiceManager();
        Colorprj.Masters.SubProductManager spm = new Colorprj.Masters.SubProductManager();
        BuyerManager bm = new BuyerManager();
        SalesManManager oSalesManManager = new SalesManManager();  
        public frmInvoice()
        {
            InitializeComponent();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            frmChallanSelection cs = new frmChallanSelection();
            cs.valueFromParent  =Convert.ToInt16(cboParty.SelectedValue)  ;
            if (cs.ShowDialog() == DialogResult.OK)
            {

                String SelectedChallanIds = cs.ItemToRead;
                String SelectedChallanNos = cs.getChallanNos;

                if (!string.IsNullOrEmpty(SelectedChallanIds)) {
                    //txtChallanNos.Text = SelectedChallanIds;
                    txtChallanNos.Text = SelectedChallanNos;
                    List<Invoice.InvoiceDetailEntity> pdList = cm.GetChallanProduct(SelectedChallanIds);
                    dataGridView2.RowCount = pdList.Count;
                    int row = 0;
                    foreach (Invoice.InvoiceDetailEntity pdEntity in pdList)
                    {

                        //dataGridView2["Product", row].Value = pdEntity.ProductId;
                        dataGridView2["SubProduct", row].Value = pdEntity.SubproductId;
                        dataGridView2["Qty", row].Value = pdEntity.Qty;
                        dataGridView2["Rate", row].Value = pdEntity.Rate;
                        dataGridView2["Amount", row].Value = pdEntity.Amount;
                        //dataGridView2["InvoiceDetId", row].Value = pdEntity.InvoiceDetailId;
                        dataGridView2.Enabled   =false;
                        dataGridView2.CausesValidation = false;
                        row++;

                    }

                    txtTotal.Text = Total().ToString("F2");
                    doInvAmount();
                }
            }


        }

        private void frmInvoice_Load(object sender, EventArgs e)
        {
            // TODO: This line of code loads data into the 'colorPrjBuyer.Buyer' table. You can move, or remove it, as needed.
            //this.buyerTableAdapter.Fill(this.colorPrjBuyer.Buyer);

            //DataSet dsTables = new DataSet();
            //dsTables = pmd.GetMultipleTableDataset();
            //dsTables.Tables[0].TableName = "Product";
            //dsTables.Tables[1].TableName = "subProduct";

            //// set up ParentBS and ChildBS and filteredChildBS
            //parentBS.DataSource = dsTables;
            //parentBS.DataMember = "Product";

            //childBS.DataSource = dsTables;
            //childBS.DataMember = "subProduct";

            //filteredChildBS.DataSource = dsTables;
            //filteredChildBS.DataMember = "subProduct";

            //// bind the regionComboBoxColumn to the parentBS
            //this.Product.DataSource = parentBS;
            //this.Product.DisplayMember = "productName";
            //this.Product.ValueMember = "productId";

            // bind the territoryComboBoxColumn to the childBS

            cboParty.DataSource = bm.GetAllBuyers(1).Tables[0];
            cboParty.DisplayMember = "BuyerName";
            cboParty.ValueMember = "BuyerId"; 

            this.SubProduct.DataSource = spm.GetAllProducts().Tables[0] ;
            this.SubProduct.DisplayMember = "subproductName";
            this.SubProduct.ValueMember = "subproductId";
            txtInvoiceNo.Text = cm.GetNextInvNo().ToString(); 
            //dtpDueDate.Value = DateTime.Now.AddDays(15) ;   
            cboSalesMan.DataSource = oSalesManManager.GetAllSalesMan().Tables[0];
            cboSalesMan.DisplayMember = "SalesManName";
            cboSalesMan.ValueMember = "SalesManId"; 
        }


        private Invoice.InvoiceHeadEntity getFormData()
        {
            Invoice.InvoiceHeadEntity phEntity = new Colorprj.Invoice.InvoiceHeadEntity();
            phEntity.BuyerId = Convert.ToInt16(cboParty.SelectedValue);
            phEntity.InvoiceNo = txtInvoiceNo.Text;
            phEntity.InvoiceDate = dtInvoiceDate.Value;
            phEntity.DueDate  = dtpDueDate.Value;
            phEntity.OrderDate  = dtODate.Value;
            phEntity.Mop = txtMop.Text  ;
            phEntity.DespachedDate  = dtDDate.Value;
            phEntity.DespachedThrough = txtDThrough.Text;
            phEntity.Destination  = txtDestination.Text ;
            phEntity.VatTaxPer =Utility.getIntVal (txtVatPer.Text);
            phEntity.VatTaxAmount = Utility.getDblVal(txtVatAmt.Text);
            phEntity.TotalAmount = Utility.getDblVal(txtTotal.Text);
            phEntity.InvAmount  = Utility.getDblVal(txtInvAmount.Text);
            phEntity.ChallanNos = txtChallanNos.Text;
            phEntity.CstPer  = Utility.getIntVal(txtCstPer.Text);
            phEntity.CstAmount = Utility.getDblVal(txtCSTAmt.Text);

            phEntity.TotalAmount = Utility.getDblVal(txtTotal.Text);
            phEntity.SalesManId = Convert.ToInt16(cboSalesMan.SelectedValue);

            if (!txtInvoiceHeadId.Text.Trim().Equals(""))
            {
                phEntity.InvoiceHeadId = Convert.ToInt16(txtInvoiceHeadId.Text);
            }

            List<Invoice.InvoiceDetailEntity> pdEntityList = new List<Colorprj.Invoice.InvoiceDetailEntity>();
            int rowCnt = 0;
            for (rowCnt = 0; rowCnt < dataGridView2.RowCount; rowCnt++)
            {
                //int prdId = Convert.ToInt16(dataGridView2["Product", rowCnt].Value);
                //int subPrdId = Convert.ToInt16(dataGridView2["Subproduct", rowCnt].Value);
                //int qty = Convert.ToInt16(dataGridView2["Qty", rowCnt].Value);
                //if (qty > 0)
                //{
                Invoice.InvoiceDetailEntity pdEntity = new Colorprj.Invoice.InvoiceDetailEntity();
                //pdEntity.ProductId = Convert.ToInt16(dataGridView2["Product", rowCnt].Value);
                pdEntity.OldQty = Convert.ToDecimal(dataGridView2["OldQty", rowCnt].Value);
                pdEntity.Qty = Convert.ToDecimal(dataGridView2["Qty", rowCnt].Value);
                pdEntity.Rate = Convert.ToDecimal(dataGridView2["Rate", rowCnt].Value);
                pdEntity.Amount = Convert.ToDecimal(dataGridView2["Amount", rowCnt].Value);
                pdEntity.SubproductId = Convert.ToInt16(dataGridView2["Subproduct", rowCnt].Value);
                pdEntity.InvoiceDetailId = Convert.ToInt16(dataGridView2["InvoiceDetId", rowCnt].Value);
                if (pdEntity.Qty > 0 || pdEntity.InvoiceDetailId > 0)
                {
                    pdEntityList.Add(pdEntity);
                }
                //}
            }
            phEntity.InvoiceDetailList = pdEntityList;
            return phEntity;
        }


        private void btnSave_Click(object sender, EventArgs e)
        {
            Invoice.InvoiceHeadEntity phEntity = getFormData();
            if (phEntity.BuyerId == 0) {

                MessageBox.Show("please select buyer ");
                return; 
            }
            if (phEntity.SalesManId  == 0)
            {

                MessageBox.Show("please select Sales Man ");
                return;
            }
            if (phEntity.InvoiceDetailList.Count == 0) {

                MessageBox.Show("please add products ");  
            }
            else
            {
                Invoice.InvoiceManager cm = new Invoice.InvoiceManager();
                cm.AddInvoice(phEntity);
                ClearForm(this.Controls);
            }
        }
        public void ClearForm(Control.ControlCollection coll)
        {
            // Control.ControlCollection coll = this.Controls;
            dataGridView2.CausesValidation = false ;
            foreach (Control c in coll)
            {
                if (c.HasChildren) ClearForm(c.Controls);
                if (c is TextBox) c.Text = string.Empty;
                if (c is DataGridView) {
                    ((DataGridView)c).CausesValidation = false;
                    ((DataGridView)c).Rows.Clear(); 
                }
                if (c is ComboBox)
                {
                    ((ComboBox)c).SelectedIndex = -1;
                }
            }
            txtInvoiceNo.Text = cm.GetNextInvNo().ToString(); 
            groupBox1.Enabled = true; 
            btnGetChallan.Enabled = true;
            dataGridView2.Enabled = true ;
            dataGridView2.CausesValidation = true;
            btnSave.Enabled = true;
            btnUpdate.Enabled = false;
            txtTotal.Text = "";
            txtInvAmount.Text  = ""; 
        }

        //private void ClearForm()
        //{

        //    btnSave.Enabled = true;
        //    btnUpdate.Enabled = false;
        //    //this.dataGridView2.Rows.Clear();
        //    txtInvoiceHeadId.Text = "";
        //    txtTotal.Text = "";
        //    //txtPurNo.Text = "";
        //    // cboParty.SelectedIndex = -1;
        //    //foreach (Control c in Form.ControlCollection )
        //    //{
        //    //    if (c is TextBox)
        //    //    {
        //    //        ((TextBox)c).Text = ((TextBox)c).Text + ((TextBox)c).Name + "\n";
        //    //    }
        //    //}
        //    Control.ControlCollection coll = this.Controls;
        //    //List<ComboBox> list33 = GetControlsOfType<ComboBox>(coll);
        //    foreach (Control c in coll)
        //    {
        //        //if (c != null)
        //        //    Console.WriteLine(c.Text, "Index numb: " + coll.GetChildIndex(c, false));
        //        if (c is TextBox) c.Text = string.Empty;
        //        if (c is DataGridView) { ((DataGridView)c).Rows.Clear(); }
        //        if (c is ComboBox)
        //        {
        //            ((ComboBox)c).SelectedIndex = -1;
        //        }
        //    }

        //}


        private void dataGridView2_EditingControlShowing(object sender, DataGridViewEditingControlShowingEventArgs e)
        {
          

        }

        private void dataGridView2_CellValueChanged(object sender, DataGridViewCellEventArgs e)
        {


            ////if (e.ColumnIndex == Product.Index)
            ////{
            ////    // clear the cell value of the territory column in the same row
            ////    //if (this.dataGridView2.DataSource.GetType() == typeof(DataTable))
            ////    //{
            ////    //    this.dataGridView2.Rows[e.RowIndex].Cells[SubProduct.Index].Value = DBNull.Value;
            ////    //}
            ////    //else
            ////    //{
            ////    if (e.RowIndex >= 0)
            ////        this.dataGridView2.Rows[e.RowIndex].Cells[SubProduct.Index].Value = null;

            ////    //}
            ////}


            if (e.RowIndex >= 0 && e.ColumnIndex == 0)
            {

                int myval = Convert.ToInt16(this.dataGridView2.Rows[e.RowIndex].Cells[e.ColumnIndex].Value);
                Colorprj.Masters.SubProduct sp = cm.GetSubProductById(myval);
                this.dataGridView2.Rows[e.RowIndex].Cells["Rate"].Value = sp.SaleRate;
                this.dataGridView2.Rows[e.RowIndex].Cells["Stock"].Value = sp.Stock;

            }


        }
        private void dataGridView2_RowLeave(object sender, DataGridViewCellEventArgs e)
        {


            if (dataGridView2[0, e.RowIndex].Value != null && dataGridView2[1, e.RowIndex].Value != null && Convert.ToInt16(dataGridView2[2, e.RowIndex].Value) != 0 && Convert.ToDecimal(dataGridView2[3, e.RowIndex].Value) != 0)
            {

                // string aa = dataGridView2[1, e.RowIndex].Value.ToString() ;
                dataGridView2.AllowUserToAddRows = true;

            }
            else { dataGridView2.AllowUserToAddRows = false; }
        }

        private void dataGridView2_CellValidated(object sender, DataGridViewCellEventArgs e)
        {
            dataGridView2["Amount", e.RowIndex].Value = Convert.ToDecimal(dataGridView2["Rate", e.RowIndex].Value) * Convert.ToDecimal(dataGridView2["Qty", e.RowIndex].Value);
            
            if (dataGridView2.Rows.Count > 0)
            {
                txtTotal.Text = Total().ToString("F2");
                doInvAmount();
            }

        }
        private double Total()
        {
            double tot = 0;
            int i = 0;
            for (i = 0; i < dataGridView2.Rows.Count; i++)
            {
                tot = tot + Convert.ToDouble(dataGridView2.Rows[i].Cells["Amount"].Value);
            }
            return tot;
        }

        private bool IsDuplicate(string spvalue,int curRow)
        {
            bool retval = false;
            int rowCnt = 0;
            System.Collections.Hashtable hash = new System.Collections.Hashtable();

            for (rowCnt = 0; rowCnt < dataGridView2.RowCount - 1; rowCnt++)
            {
                String SubproductId = dataGridView2["Subproduct", rowCnt].FormattedValue.ToString();
                if (hash.Contains(spvalue))
                {
                    retval = true;
                    break;
                }
                else
                {
                    if (curRow != rowCnt)
                    {
                        hash.Add(SubproductId, SubproductId);
                    }
                }

            }
            return retval;
        }

        private void dataGridView2_CellEndEdit(object sender, DataGridViewCellEventArgs e)
        {
            dataGridView2.Rows[e.RowIndex].ErrorText = String.Empty;

        }
        private void dataGridView2_CellValidating(object sender, DataGridViewCellValidatingEventArgs e)
        {
            string headerText = dataGridView2.Columns[e.ColumnIndex].HeaderText;


            if (headerText.Equals("Sub-prd"))
            {
                if (string.IsNullOrEmpty(e.FormattedValue.ToString()))
                {
                    dataGridView2.Rows[e.RowIndex].ErrorText =
                        "Sub Product must not be empty";
                    e.Cancel = true;
                }

                if (IsDuplicate(e.FormattedValue.ToString(), e.RowIndex) && dataGridView2.Rows[e.RowIndex].Cells["InvoiceDetId"].Value == null)
                {
                    dataGridView2.Rows[e.RowIndex].ErrorText =
                                "Sub Product Allready Exist";
                    if (dataGridView2.Enabled)
                    {
                        e.Cancel = true;
                    }
                }

            }
            if (headerText.Equals("Qty"))
            {
                double curQty = Utility.getDblVal(e.FormattedValue.ToString());
                double OldQty = Utility.getDblVal(dataGridView2.Rows[e.RowIndex].Cells["OldQty"].Value);
                double StockQty = Utility.getDblVal(dataGridView2.Rows[e.RowIndex].Cells["Stock"].Value);
                if (curQty > OldQty + StockQty)
                {

                    dataGridView2.Rows[e.RowIndex].ErrorText =
                                    "Qty is greater then avialable qty in stock";
                    if (dataGridView2.Enabled)
                    {
                        e.Cancel = true;
                    }
                }
            }


        }

        private void txtVatPer_TextChanged(object sender, EventArgs e)
        {
            doInvAmount();
            decimal vtpAmount = Utility.getDecimalVal(txtVatPer.Text);
            if (vtpAmount != 0) { txtCstPer.Enabled = false; } else { txtCstPer.Enabled = true; }
        }
        private void doInvAmount(){


            decimal tAmount = Utility.getDecimalVal(txtTotal.Text);
            decimal vatAmt = (tAmount * Utility.getDecimalVal(txtVatPer.Text) / 100);
            //decimal cstAmount = Utility.getDecimalVal(txtTotal.Text);
            decimal cstAmt = (tAmount * Utility.getDecimalVal(txtCstPer.Text) / 100);
            txtVatAmt.Text = vatAmt.ToString("F2");
            txtCSTAmt.Text = cstAmt.ToString("F2");
            txtInvAmount.Text = Convert.ToString((tAmount + Utility.getDecimalVal(txtVatAmt.Text)+ Utility.getDecimalVal(txtCSTAmt.Text)));
            //if (cstAmt != 0) { txtVatPer.Enabled = false; txtCstPer.Enabled = true; } else { txtCstPer.Enabled = false; txtVatPer.Enabled = true; }
            //if (vatAmt != 0) { txtCstPer.Enabled = false; txtVatPer.Enabled = true; } else { txtVatPer.Enabled = false; txtCstPer.Enabled = true; }
        }
        private void btnEdit_Click(object sender, EventArgs e)
        {
            frmInvSearch ps = new frmInvSearch();
            Invoice.InvoiceManager cm = new Colorprj.Invoice.InvoiceManager();
            if (ps.ShowDialog() == DialogResult.OK)
            {
                groupBox1.Enabled = false; 
                int InvoiceId = Convert.ToInt16(ps.ItemToRead);


                Invoice.InvoiceHeadEntity phEntity = cm.GetInvoice(InvoiceId);
                txtInvoiceHeadId.Text = InvoiceId.ToString();
                txtInvoiceNo.Text = phEntity.InvoiceNo;
                dtInvoiceDate.Value = phEntity.InvoiceDate;
                dtpDueDate.Value = phEntity.DueDate;
                cboParty.SelectedValue = phEntity.BuyerId;
                txtTotal.Text = phEntity.TotalAmount.ToString();
                txtDestination.Text = phEntity.Destination.ToString();
                txtDThrough .Text = phEntity.DespachedThrough.ToString();
                txtVatPer.Text = phEntity.VatTaxPer.ToString();
                txtVatAmt.Text = phEntity.VatTaxAmount.ToString() ;
                dtDDate.Value  = phEntity.DespachedDate;
                dtODate.Value  = phEntity.OrderDate;
                txtChallanNos.Text = phEntity.ChallanNos ;
                txtMop.Text = phEntity.Mop.ToString();
                //txtGtotal.Text = phEntity.GTotal.ToString();
                cboSalesMan.SelectedValue = phEntity.SalesManId ;
                btnGetChallan.Enabled = false; 

                dataGridView2.RowCount = phEntity.InvoiceDetailList.Count + 1;
                int row = 0;
                foreach (Invoice.InvoiceDetailEntity pdEntity in phEntity.InvoiceDetailList)
                {

                   // dataGridView2["Product", row].Value = pdEntity.ProductId;
                    dataGridView2["SubProduct", row].Value = pdEntity.SubproductId;
                    dataGridView2["SubProduct", row].ReadOnly = true;
                    dataGridView2["Qty", row].Value = pdEntity.Qty;
                    dataGridView2["OldQty", row].Value = pdEntity.Qty;
                    dataGridView2["Rate", row].Value = pdEntity.Rate;
                    dataGridView2["Amount", row].Value = pdEntity.Amount;
                    dataGridView2["InvoiceDetId", row].Value = pdEntity.InvoiceDetailId;
                    row++;

                }

                if (!txtChallanNos.Text.Trim().Equals(""))
                {
                    dataGridView2.Enabled = false;
                    dataGridView2.CausesValidation = false;
                }
                else {

                    dataGridView2.Enabled = true;
                    dataGridView2.CausesValidation = true;
                
                }

                btnSave.Enabled = false;
                btnUpdate.Enabled = true;
            }
        }

        private void btnUpdate_Click(object sender, EventArgs e)
        {
            try
            {
                Invoice.InvoiceHeadEntity phEntity = getFormData();
                Invoice.InvoiceManager pm = new Colorprj.Invoice.InvoiceManager();
                pm.UpdInvoice(phEntity);
            } catch (Exception ex ){
                MessageBox.Show(ex.Message);  
            }
            ClearForm(this.Controls);
        }

        private void dataGridView2_CellContentClick(object sender, DataGridViewCellEventArgs e)
        {

        }

        private void cboParty_SelectedIndexChanged(object sender, EventArgs e)
        {
            //ClearForm(this.Controls); 
        }

        private void btnCancel_Click(object sender, EventArgs e)
        {
            ClearForm(this.Controls);
        }

        private void dtInvoiceDate_ValueChanged(object sender, EventArgs e)
        {

        }

        private void dataGridView2_CellLeave(object sender, DataGridViewCellEventArgs e)
        {
            dataGridView2["Amount", e.RowIndex].Value = Convert.ToDecimal(dataGridView2["Qty", e.RowIndex].Value) * Convert.ToDecimal(dataGridView2["Rate", e.RowIndex].Value);
            dataGridView2.AllowUserToAddRows = true;
        }

        private void label11_Click(object sender, EventArgs e)
        {

        }

        private void txtInvoiceNo_TextChanged(object sender, EventArgs e)
        {

        }

        private void txtCstPer_TextChanged(object sender, EventArgs e)
        {
            doInvAmount();
            decimal cstp = Utility.getDecimalVal(txtCstPer.Text);
            if (cstp != 0) { txtVatPer.Enabled = false; } else { txtVatPer.Enabled = true; }
             
        }

        private void txtDThrough_TextChanged(object sender, EventArgs e)
        {

        }


    }
}